﻿using MediatR;
using MyMES.Domain.zyy;
using MyMES.Error;
using MyMES.Infrastructure.Interface;
using MyMES.Read.API.Application.Commends.Productionwork;

namespace MyMES.Read.API.Application.CommendHandlers.Productionwork
{
    public class GetProductionworkCommendHandlers : IRequestHandler<GetProductionworkCommends, APIPaging<List<WorkOrder>>>
    {

        private readonly IBaseRepository<WorkOrder>  workordersRepository;

        public GetProductionworkCommendHandlers(IBaseRepository<WorkOrder> workordersRepository)
        {
            this.workordersRepository = workordersRepository;
        }

        /// <summary>
        /// 获取生产工单
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIPaging<List<WorkOrder>>> Handle(GetProductionworkCommends request, CancellationToken cancellationToken)
        {
            try
            {
                APIPaging<List<WorkOrder>> result = new APIPaging<List<WorkOrder>>();
                result.Code = APIEnum.查询成功;
                result.Msg = "显示成功";
                string sql = "select *  from WorkOrder where IsDlete=false ORDER BY WorkOrderId  DESC";
                var list = await workordersRepository.SelectAsync(sql);
                if (!string.IsNullOrEmpty(request.WorkOrderCoding))
                {
                    list = list.Where(x => x.WorkOrderCoding.Contains(request.WorkOrderCoding)).ToList();
                }

                if (!string.IsNullOrEmpty(request.ProductName))
                {
                    list = list.Where(x => x.ProductName.Contains(request.ProductName)).ToList();
                }
                if (!string.IsNullOrEmpty(request.CustomerNamwe))
                {
                    list = list.Where(x => x.CustomerNamwe.Contains(request.CustomerNamwe)).ToList();
                }
                if (request.RequestDate != null)
                {
                    var filterDate = request.RequestDate.Value.Date.AddDays(1);
                    list = list.Where(x => x.RequestDate.Date == filterDate).ToList();

                }
                result.TotalCount = list.Count;
                result.TotalPage = (int)Math.Ceiling(result.TotalCount * 1.0 / request.pageSize);
                list = list.Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
                result.data = list;
                return result;


            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
